package com.weixin.project.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weixin.project.Annotation.AdminAccess;
import com.weixin.project.Common.Enum.LikedStatus;
import com.weixin.project.Common.Enum.ModuleType;
import com.weixin.project.Common.Enum.UserType;
import com.weixin.project.Entity.Comment;
import com.weixin.project.Entity.ForumQuestion;
import com.weixin.project.Entity.User;
import com.weixin.project.Service.CommonService;
import com.weixin.project.Service.ForumService;
import com.weixin.project.Service.MsgService;
import com.weixin.project.Service.UserService;
import com.weixin.project.Util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class ForumController {
    @Value("${logging.pattern.dateformat}")
    String dateFormat;
    @Autowired
    UserService userService;
    @Autowired
    ForumService forumService;
    @Autowired
    CommonService commonService;
    @Autowired
    MsgService msgService;
    @PostMapping("/question/upload")
    JSONObject raiseQuestion(@RequestBody JSONObject params,
                             HttpServletRequest request){
        User currentUser = userService.findCurrentUser(request);
        if(currentUser == null){
            return ResponseUtil.userNotFind();
        }
        ForumQuestion question = new ForumQuestion();
        question.setOriginTime(new Date());
        question.setOriginId(currentUser.getId());
        question.setTitle(params.getString("title"));
        question.setContent(params.getString("text"));
        question.setImageText(params.getString("pic_text"));
        question.setCoverSrc(params.getString("cover_src"));
        forumService.storeQuestion(question);
        return ResponseUtil.success();
    }

    @GetMapping("/question/get_question")
    JSONObject getQuestion(HttpServletRequest request,
            @RequestParam("id") Integer questionId){
        User currentUser = userService.findCurrentUser(request);
        ForumQuestion question = forumService.findQuestion(questionId);
        JSONObject ret = new JSONObject();
        JSONObject questionObj = new JSONObject();
        questionObj.put("text", question.getContent());
        questionObj.put("title", question.getTitle());
        questionObj.put("id", question.getId());
        User origin = userService.findUser(question.getOriginId());
        questionObj.put("user_name", origin.getName());
        questionObj.put("user_img", origin.getImage());
        questionObj.put("read_count", forumService.getReadCount(question));
        questionObj.put("time", new SimpleDateFormat(dateFormat).format(question.getOriginTime()));
        ret.put("question",questionObj);
        JSONArray commentList = new JSONArray();
        List<Comment> comments = commonService.findComments(questionId, ModuleType.FORUM);
        for (Comment comment:comments){
            JSONObject commentObj = new JSONObject();
            User answerer = userService.findUser(comment.getAnswererId());
            commentObj.put("user_name", answerer.getName());
            commentObj.put("user_img", answerer.getImage());
            commentObj.put("comment_text", comment.getContent());
            commentObj.put("time", new SimpleDateFormat(dateFormat).format(comment.getCreateTime()));
            commentObj.put("good", commonService.countLikesOfComment(comment));
            commentObj.put("id", comment.getId());
            commentObj.put("has_good", LikedStatus.getBool(
                    commonService.ifUserHasLiked(comment.getId(), currentUser.getId())));
            commentList.add(commentObj);
        }
        ret.put("comments", commentList);
        forumService.incReadCount(question);
        return ResponseUtil.success("",ret);
    }

    @GetMapping("/question/get_questions_list")
    JSONObject getQuestionList(@RequestParam("page") Integer page){
        page -- ;
        Page<ForumQuestion> questionsPage = forumService.findQuestions(page);
        List<ForumQuestion> questions = questionsPage.getContent();
        JSONArray questionList = new JSONArray();
        for (ForumQuestion question:questions){
            JSONObject questionObj = new JSONObject();
            questionObj.put("title", question.getTitle());
            questionObj.put("id", question.getId());
            questionObj.put("read_count", forumService.getReadCount(question));
            questionObj.put("comment_count", commonService.findComments(question.getId(), ModuleType.FORUM).size());
            User originUser = userService.findUser(question.getOriginId());
            questionObj.put("user_id", originUser.getUserId());
            questionObj.put("user_img", originUser.getImage());
            questionObj.put("user_name", originUser.getName());
            questionObj.put("time", new SimpleDateFormat(dateFormat).format(question.getOriginTime()));
            questionObj.put("cover_src", question.getCoverSrc());
            questionList.add(questionObj);
        }
        JSONObject ret = new JSONObject();
        ret.put("questions",questionList);
        ret.put("all_pages",questionsPage.getTotalPages());
        ret.put("question_count", forumService.countAllQuestions());
        return ResponseUtil.success("",ret);
    }

    @GetMapping("/question/get_my_question")
    JSONObject getMyQuestions(HttpServletRequest request,
                              @RequestParam("page") Integer page){
        page -- ;
        User currentUser = userService.findCurrentUser(request);
        if(currentUser == null){
            return ResponseUtil.userNotFind();
        }
        Page<ForumQuestion> questionPage = forumService.findQuestionsOfUser(page, currentUser.getId());
        List<ForumQuestion> questions = questionPage.getContent();
        JSONArray questionList = new JSONArray();
        for (ForumQuestion question:questions) {
            JSONObject questionObj = new JSONObject();
            questionObj.put("title", question.getTitle());
            questionObj.put("id", question.getId());
            questionObj.put("read_count", forumService.getReadCount(question));
            questionObj.put("comment_count", commonService.findComments(question.getId(), ModuleType.FORUM).size());
            questionObj.put("cover_src", question.getCoverSrc());
            questionList.add(questionObj);
        }
        JSONObject ret = new JSONObject();
        ret.put("questions",questionList);
        ret.put("all_pages",questionPage.getTotalPages());
        ret.put("question_counts", forumService.countQuestionsOfUser(currentUser.getId()));
        return ResponseUtil.success("",ret);
    }

    @PostMapping("/question/delete_question")
    JSONObject deleteQuestion(HttpServletRequest request,
                              @RequestBody JSONObject params){
        User currentUser = userService.findCurrentUser(request);
        Integer questionId = params.getInteger("id");
        ForumQuestion question = forumService.findQuestion(questionId);
        if(!currentUser.getType().equals(UserType.ADMIN) && currentUser.getId() != question.getOriginId()){
            return ResponseUtil.accessError();
        }
        //自己删除自己的东西不用发消息
        if (!currentUser.getId().equals(question.getOriginId())){
            msgService.sendDeleteMessage(question.getOriginId(), "Question", question.getTitle());
        }
        forumService.deleteQuestion(question);
        return ResponseUtil.success();
    }

}
